﻿using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using YNTK.Common.Const;
using YNTK.Data.MongoDB.Repositorie;
using YNTK.DataEncryption;
using YNTK.Employees.Entitys.Entity;
using YNTK.EventBridge;
using YNTK.Mapster;
using YNTK.System.Entitys.Permission;

namespace YNTK.Common.Core.Handler
{
    /// <summary>
    /// 员工信息同步处理handler
    /// </summary>
    [EventHandler]
    public class EmployeeEventHandler: IEventHandler
    {
        private readonly ISqlSugarRepository<EmployeesEntity> _employeesRepository;//员工仓储
        private readonly IMongoDBRepository<EmployeesEntity> _employeesMongoDbRepository;//员工mongodb仓储
        private readonly ISqlSugarRepository<UserEntity> _tkUserRepository;//用户仓储
        private readonly IMongoDBRepository<UserEntity> _tkUserMongoDbRepository;//用户mongodb仓储

        private readonly SqlSugarScope _db;
        private readonly ITenant _tenant;

        private readonly string _users = "base_users";//mongodb中用户数据集名称
        private readonly string _employees = "employees_rosters";//mongodb中员工数据集名称

        /// <summary>
        /// 构造方法依赖注入
        /// </summary>
        /// <param name="employeesRepository">员工仓储</param>
        /// <param name="employeesMongoDbRepository">员工mongodb仓储</param>
        /// <param name="tkUserRepository">用户仓储</param>
        /// <param name="tkUserMongoDbRepository">用户mongodb仓储</param>
        public EmployeeEventHandler(ISqlSugarRepository<EmployeesEntity> employeesRepository,
            IMongoDBRepository<EmployeesEntity> employeesMongoDbRepository,
            ISqlSugarRepository<UserEntity> tkUserRepository,
            IMongoDBRepository<UserEntity> tkUserMongoDbRepository)
        {
            _employeesRepository = employeesRepository;
            _employeesMongoDbRepository = employeesMongoDbRepository;
            _tkUserRepository = tkUserRepository;
            _tkUserMongoDbRepository = tkUserMongoDbRepository;
            _db = _employeesRepository.Context;
            _tenant = _db;
        }

        /// <summary>
        /// 添加员工信息
        /// </summary>
        /// <returns></returns>
        [EventMessage]
        public async Task Add(EventMessage<EmployeesEntity> eventPayload)
        {
            var entity = eventPayload.Payload;
            if ((await GetEmployeesInfoAsync(e => e.Id == entity.Id)) != null) return;
            //添加员工信息到sqlserver
            await _db.Insertable(entity).ExecuteReturnEntityAsync();
            //添加员工信息到mongodb
            await _employeesMongoDbRepository.AddAsync(entity, _employees);
        }

        /// <summary>
        /// 修改员工信息
        /// </summary>
        /// <returns></returns>
        [EventMessage]
        public async Task Update(EventMessage<EmployeesEntity> eventPayload)
        {
            var model= eventPayload.Payload;
            var entity = await GetEmployeesInfoAsync(e => e.Id == model.Id);
            if (entity != null)
            {
                entity = model.Mapper(entity);
                //保存员工信息到sqlserver
                await _db.Updateable(entity).WhereColumns(it => new { it.Id }).ExecuteCommandAsync();
                //保存员工信息到mongodb
                await _employeesMongoDbRepository.UpdateAsync(entity, _employees, m => m.Id == entity.Id);
            }
            else
            {
                await Add(eventPayload);
            }
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <returns></returns>
        [EventMessage]
        public async Task Delete(EventMessage<string> eventPayload)
        {
            string id= eventPayload.Payload;
            var entity = await GetEmployeesInfoAsync(e => e.Id == id);
            if (entity != null)
            {
                //从sqlserver中删除员工信息
                await _employeesRepository.DeleteAsync(r => r.Id == id);
                //从mongodb中删除员工信息
                await _employeesMongoDbRepository.DeleteAsync(_employees, m => m.Id == id);
            }
        }

        /// <summary>
        /// 分配用户角色
        /// </summary>
        /// <returns></returns>
        [EventMessage]
        public async Task AuthorizationUsers(EventMessage<List<UserEntity>> eventPayload)
        {
            var users= eventPayload.Payload;
            if (!users.Any()) return;
            var userIds = users.Select(r => r.Id).ToList();
            var entitys = await _employeesMongoDbRepository.GetListAsync(_employees,m=>userIds.Contains(m.Id));
            if (!entitys.Any()) entitys = await _employeesRepository.Entities.Where(r => userIds.Contains(r.Id)).ToListAsync();
            if (!entitys.Any()) return;
            entitys.ForEach(user =>
            {
                user.RoleId = users.FirstOrDefault(u => u.Id == user.Id)?.RoleId;
            });
            //更新员工角色
            await _db.Updateable(entitys).WhereColumns(it => new { it.Id }).ExecuteCommandAsync();
            await _employeesMongoDbRepository.UpdateManayAsync(entitys, _employees);
        }

        /// <summary>
        /// 授权用户角色
        /// </summary>
        /// <returns></returns>
        [EventMessage]
        public async Task AuthorizationRole(EventMessage<UserEntity> eventPayload)
        {
            var user= eventPayload.Payload;
            var entity = await GetEmployeesInfoAsync(e => e.Id == user.Id);
            if (entity != null)
            {
                //更新员工角色
                entity.RoleId = user.RoleId;
                await _db.Updateable(entity).WhereColumns(it => new { it.Id }).ExecuteCommandAsync();
                await _employeesMongoDbRepository.UpdateAsync(entity, _employees, m => m.Id == entity.Id);
            }
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="eventPayload"></param>
        /// <returns></returns>
        [EventMessage]
        public async Task UpadteUserInfo(EventMessage<Tuple<EmployeesEntity, string>> eventPayload)
        {
            var employee = eventPayload.Payload.Item1;
            var entity = await GetUserInfoAsync(u => u.Id == employee.Id && u.DeleteMark==null);
            if (entity != null)
            {
                entity = employee.Mapper(entity);
                entity.Gender = employee.Sex == 0 ? 1 : 2;
                entity.LastModifyUserId= eventPayload.Payload.Item2;
                //保存用户信息到sqlserver
                await _tkUserRepository.Context.Updateable(entity).ExecuteCommandAsync();
                //保存用户信息到mongodb
                await _tkUserMongoDbRepository.UpdateAsync(entity, _users, m => m.Id == entity.Id);
            }
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <returns></returns>
        [EventMessage]
        public async Task AddUserInfo(EventMessage<Tuple<EmployeesEntity, string>> eventPayload)
        {
            var employee = eventPayload.Payload.Item1;
            var user = await GetUserInfoAsync(u => u.Id == employee.Id && u.DeleteMark == null);
            if (user == null)
            {
                var entity = employee.Adapt<UserEntity>();
                //账号类型【0.平台运营人员 1.超级管理员 2.组织管理员 3.组织用户 4.第三方登录用户 5.游客用户】
                entity.AccountType =3;
                entity.Gender = employee.Sex == 0 ? 1 : 2;
                entity.CreatorUserId = eventPayload.Payload.Item2;
                entity.DeleteMark = null;
                entity.EnabledMark = 1;
                entity.Secretkey = Guid.NewGuid().ToString();
                entity.Password = MD5Encryption.Encrypt(CommonConst.DEFAULT_PASSWORD + entity.Secretkey);

                //添加用户信息到sqlserver
                await _tkUserRepository.Context.Insertable(entity).ExecuteReturnEntityAsync();
                //添加用户信息到mongodb
                await _tkUserMongoDbRepository.AddAsync(entity, _users);
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <returns></returns>
        [EventMessage]
        public async Task DeleteUserInfo(EventMessage<string> eventPayload)
        {
            string userId = eventPayload.Payload;
            var user = await GetUserInfoAsync(u => u.Id == userId && u.DeleteMark == null);
            if (user != null)
            {
                await _tkUserRepository.Context.Deleteable(user).ExecuteCommandAsync();
                await _tkUserMongoDbRepository.DeleteAsync(_users, m => m.Id == userId);
            }
        }


        /// <summary>
        /// 根据条件获取员工信息
        /// </summary>
        /// <param name="where">条件</param>
        /// <returns></returns>
        private async Task<EmployeesEntity> GetEmployeesInfoAsync(Expression<Func<EmployeesEntity, bool>> where)
        {
            //从从mongodb中获取
            var entity = await _employeesMongoDbRepository.GetAsync(_employees, where);
            //再从sqlserver中获取
            if (entity == null) entity = await _employeesRepository.FirstOrDefaultAsync(where);
            return entity;
        }

        /// <summary>
        /// 根据条件获取用户信息
        /// </summary>
        /// <param name="where">条件</param>
        /// <returns></returns>
        private async Task<UserEntity> GetUserInfoAsync(Expression<Func<UserEntity, bool>> where)
        {
            //从从mongodb中获取
            var entity = await _tkUserMongoDbRepository.GetAsync(_users, where);
            //再从sqlserver中获取
            if (entity == null) entity = await _tkUserRepository.FirstOrDefaultAsync(where);
            return entity;
        }

    }
}
